const express = require('express');
const router = express.Router();
const Event = require('../models/Event');

// 获取历史事件（分页）
router.get('/', async (req, res) => {
  try {
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 20;
    const events = await Event.getAll(page, limit);
    
    // 获取总数用于分页
    const total = await new Promise((resolve) => {
      require('../db/database').get(
        "SELECT COUNT(*) as count FROM events",
        (err, row) => resolve(row?.count || 0)
      );
    });
    
    res.json({
      success: true,
      data: events,
      pagination: {
        page,
        limit,
        total,
        totalPages: Math.ceil(total / limit)
      }
    });
  } catch (err) {
    res.status(500).json({ success: false, error: '数据库查询失败' });
  }
});

// 按状态过滤事件
router.get('/:status', async (req, res) => {
  try {
    const validStatuses = ['pending', 'acknowledged', 'resolved'];
    const status = req.params.status.toLowerCase();
    
    if (!validStatuses.includes(status)) {
      return res.status(400).json({ 
        success: false,
        error: '无效的状态值' 
      });
    }
    
    const events = await Event.getByStatus(status);
    res.json({ success: true, data: events });
  } catch (err) {
    res.status(500).json({ success: false, error: '数据库查询失败' });
  }
});

module.exports = router;